package com.czq.websocket.service.impl;

import com.czq.websocket.server.WebSocketServer;
import com.czq.websocket.service.MsgService;
import com.czq.websocket.utils.RedisUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author czq
 * @date 2020-5-17
 */
@Service("MsgService")
public class MsgServiceImpl implements MsgService {

    @Resource
    RedisUtils redisUtils;

    @Resource
    WebSocketServer webSocketServer;

    /**
     * 用户消息队列名
     */
    public static final String LIST_NAME = "user:msg:list:";

    /**
     * 用户是否拉取
     */
    public static final String IS_PULL = "user:msg:list:pull:";

    /**
     * 拉取标识符
     */
    public static final String PUll_TRUE = "1";

    /**
     * 获取用户消息列表
     *  @param userId 用户id
     *
     */

    @Override
    public void getMsgList(String userId) {
        // TODO 解决方案 1.可以改成 Redis 订阅消费者模式  2. webSocket 发送心跳数据
        new Runnable(){
            @Override
            public void run() {
                try {
                    String userIndexKey = LIST_NAME + userId;
                    String userIsPull = IS_PULL + userId;
                    // 判断用户号是否存在
                    boolean isExistUser = redisUtils.hasKey(userIndexKey);
                    boolean isPull = redisUtils.hasKey(userIsPull);

                    while (true) {
                        if (isExistUser && isPull && PUll_TRUE.equals(redisUtils.get(userIsPull)+"")) {
                            List userMsgList = redisUtils.lGet(userIndexKey);
                            redisUtils.set(userIsPull,"0");
                            webSocketServer.sendMsgByUserId(userId ,redisUtils.toJson(userMsgList));
                        }
                        Thread.sleep(200);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.run();
    }
}
